import { translate_block,translate_process } from "./ookay-core";

/**
 * OOKay类
 * 用于需要在类中实现运算符重载的子类的继承
 */
export default class OOkay {
    constructor () {
        let protos = Object.getOwnPropertyNames(Object.getPrototypeOf(this))
        protos.forEach((proto, key, own) => {
            if(proto != 'constructor'){
                Object.defineProperty(this, proto, {
                    value:new Function(translate_block(proto, this[proto].toString())).call(this)
                })
            }
        })
    }

    /**
     * 非继承类的注入方法
     * @param target
     */
    static inject (target) {
        let protos = Object.getOwnPropertyNames(Object.getPrototypeOf(target))
        protos.forEach((proto, key, own) => {
            if (proto != 'constructor') {
                Object.defineProperty(target, proto, {
                    value:new Function(translate_block(proto, target[proto].toString())).call(target)
                })
            }
        })
    }

    /**
     * @param fn
     * @private
     */
    static __$__(fn) {
        if(!(fn instanceof Function)){
            throw '参数错误'
        }
        (new Function(translate_block('function',fn.toString()))).call(window)()
    }

    /**
     * @param code
     * @private
     */
    static __$$__(code) {
        return new Function('console.log(this)\nreturn function() {\n' + translate_process(code) + '\n}.bind(this)()\n')
    }
}